import re

from pythonProject.spider.html_downloader import HtmlDownloader
from pythonProject.spider.product import Product


class HtmlParser:
    item_pattern = r'<li class="brick-item">[\s\S]*?</li>'
    title_pattern = r'<h3 class="title"><a href="javascript:;">([\s\S]*?)</a></h3>'
    desc_pattern = r'<p class="desc">([\s\S]*?)</p>'
    price_pattern = r'<span class="num">([\s\S]*?)</span>'

    def parser(self, html):
        """
        解析给定的html
        :param html: html
        :return: product set
        """
        items = re.findall(self.item_pattern, html)
        # print(items)

        #定义一个result，放入最终要返回的数据
        result = set()
        for i in items:
            title = re.findall(self.title_pattern, i)
            desc = re.findall(self.desc_pattern, i)
            price = re.findall(self.price_pattern, i)
            result.add(Product(title[0], desc[0], price[0]))

        return result

# 这里是测试代码，可忽略
# downloader = HtmlDownloader()
# html = downloader.download("http://127.0.0.1:8848/xiaomi-master/index.html")
# htmlParse = HtmlParser()
# result = htmlParse.parser(html)
# for i in result:
#     print(i)



